package com.freight.user.serviceimpl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.freight.core.common.exception.FreightException;
import com.freight.core.common.redis.RedisTemplateHelper;
import com.freight.core.common.utils.ObjectUtil;
import com.freight.core.common.utils.SecurityUtil;
import com.freight.core.common.vo.SearchVo;
import com.freight.core.entity.User;
import com.freight.core.service.OperationLogService;
import com.freight.core.service.UserService;
import com.freight.file.constants.FileConstant;
import com.freight.file.entity.File;
import com.freight.file.service.FileService;
import com.freight.file.util.CompanyOcrUtil;
import com.freight.file.util.FileUtils;
import com.freight.file.util.MyFileUtils;
import com.freight.file.vo.CompanyPicFileVo;
import com.freight.user.dao.CompanyLicenseDao;
import com.freight.user.dao.IdCardDao;
import com.freight.user.dto.CompanyLicenseDto;
import com.freight.user.entity.CompanyLicense;
import com.freight.user.entity.CompanyUser;
import com.freight.user.entity.IdCard;
import com.freight.user.mapper.CompanyVoMapper;
import com.freight.user.service.CompanyLicenseService;
import com.freight.user.service.CompanyUserService;
import com.freight.user.service.DriverUserService;
import com.freight.user.vo.CompanyEnterpriseVo;
import com.freight.user.vo.CompanyLicenseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 营业资格证接口实现
 *
 * @author huyingtai
 */
@Slf4j
@Service
@Transactional
public class CompanyLicenseServiceImpl implements CompanyLicenseService {

    @Autowired
    private CompanyLicenseDao companyLicenseDao;

    @Autowired
    private IdCardDao idCardDao;

    @Autowired
    private CompanyVoMapper companyVoMapper;

    @Autowired
    SecurityUtil securityUtil;

    @Autowired
    private RedisTemplateHelper redisTemplate;

    @Autowired
    UserService userService;

    @Autowired
    FileService fileService;

    @Autowired
    private OperationLogService operationLogService;

    @Autowired
    CompanyUserService companyUserService;

    @Autowired
    private DriverUserService driverUserService;

    @Override
    public CompanyLicenseDao getRepository() {
        return companyLicenseDao;
    }

    @Override
    public CompanyEnterpriseVo getCompanyEnterprise(Long userId) {

        User u = securityUtil.getCurrUser();
        CompanyEnterpriseVo companyEnterpriseVo=new CompanyEnterpriseVo();
        CompanyUser res = companyUserService.findByUserId(userId);
        if (res != null) {
            Long companyId = res.getCompanyLicenseId();
            if (companyId != null) {
                CompanyLicense companyLicense = companyLicenseDao.getOne(companyId);
                companyEnterpriseVo.setCompanyLicense(companyLicense);
            }

            Long contactsIdCardId = res.getContactsIdCardId();
            if (companyId != null) {
                IdCard contactsIdCard = idCardDao.getOne(contactsIdCardId);
                companyEnterpriseVo.setContactsIdCard(contactsIdCard);
            }
        }

        return companyEnterpriseVo;
    }

    @Override
    public Page<CompanyLicense> findByCondition(CompanyLicense companyLicense, SearchVo searchVo, Pageable pageable) {

        return companyLicenseDao.findAll(new Specification<CompanyLicense>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<CompanyLicense> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {

                // TODO 可添加你的其他搜索过滤条件 默认已有创建时间过滤
                Path<Date> createTimeField = root.get("createTime");
                // TODO 可添加你的其他搜索过滤条件 默认已有创建时间过滤
                Path<Long> userId = root.get("userId");

                List<Predicate> list = new ArrayList<>();

                // 创建时间
                if (StrUtil.isNotBlank(searchVo.getStartDate()) && StrUtil.isNotBlank(searchVo.getEndDate())) {
                    Date start = DateUtil.parse(searchVo.getStartDate());
                    Date end = DateUtil.parse(searchVo.getEndDate());
                    list.add(cb.between(createTimeField, start, DateUtil.endOfDay(end)));
                }


                Predicate[] arr = new Predicate[list.size()];
                cq.where(list.toArray(arr));
                return null;
            }
        }, pageable);
    }


    @Override
    public CompanyPicFileVo upLoadCompanyLicense(MultipartFile file, String fileConstant) {
        User u = securityUtil.getCurrUser();
        java.io.File picFile = null;
        CompanyPicFileVo res;
        try {
            picFile = MyFileUtils.convert(file);
            String image_64 = FileUtils.baiud_img_file(picFile);
            res = CompanyOcrUtil.baiDuJustCompany(image_64,redisTemplate);
            if (!ObjectUtil.isAllFieldNotNull(res)) {
                throw new FreightException("图片不清晰： 请重新上传图片");
            }
            File sfile = fileService.saveFileByUserId(file, FileConstant.COMPANY_WORK_PIC);
            res.setFileId(sfile.getId());
            res.setFilepath(sfile.getUrl());
        } catch (Exception e) {
            throw new FreightException(e.getMessage());
        }
        return res;
    }

    @Override
    public CompanyLicense getCompanyLicenseInfo(Long userId) {
        User u = securityUtil.getCurrUser();
        CompanyLicense companyLicense = null;
        CompanyUser res = companyUserService.findByUserId(userId);
        if (res != null) {
            Long companyId = res.getCompanyLicenseId();
            if (companyId != null) {
                companyLicense = companyLicenseDao.getOne(companyId);
            }
        }else {
            return new CompanyLicense();
        }
        return companyLicense;
    }

    @Override
    public String saveCompanyLicenseInfo(CompanyLicenseDto companyLicenseDto) {
        User user = securityUtil.getCurrUser();
        Long userId = companyLicenseDto.getUserId();
        User u = userService.get(userId);
        String logContent = "";

        List<CompanyLicenseVo> companyLicenseVo=companyVoMapper.getCompanyLicenseName(companyLicenseDto.getCertNo());

        if(companyLicenseVo!=null&&companyLicenseVo.size()>1){
            throw new FreightException("该公司已存在");
        }

        if (companyLicenseVo!=null&&companyLicenseVo.size()>0 && !companyLicenseVo.get(0).getUserId().equals(companyLicenseDto.getUserId())){
            throw new FreightException("该公司已存在");
        }

        CompanyUser cu = companyUserService.findByUserId(userId);
        if (cu == null) {
            cu = new CompanyUser();
            cu.setUserId(userId);
        }

        //联系人身份证
        Long contactIdCardId = cu == null ? null : cu.getContactsIdCardId();
        // 上传过身份证
        IdCard contactIdCard;
        if (contactIdCardId != null && contactIdCardId > 0) {
            contactIdCard = idCardDao.getOne(contactIdCardId);
        } else {
            contactIdCard = new IdCard();
        }

        contactIdCard.setContactPhone(companyLicenseDto.getContactPhone());
        contactIdCard.setName(companyLicenseDto.getContactName());
        contactIdCard.setNum(companyLicenseDto.getContactNum());
        contactIdCard.setEndDate(companyLicenseDto.getContactEndDate());
        contactIdCard.setIdCardBackPicFileId(companyLicenseDto.getContactIdCardBackPicFileId());
        contactIdCard.setIdCardFontPicFileId(companyLicenseDto.getContactIdCardFontPicFileId());

        contactIdCard = idCardDao.save(contactIdCard);
        cu.setContactsIdCardId(contactIdCard.getId());

        //营业执照
        Long companyLicenseId = cu.getCompanyLicenseId();

        // 上传过
        CompanyLicense companyLicense = null;
        if (companyLicenseId != null && companyLicenseId > 0) {
            companyLicense = companyLicenseDao.getOne(companyLicenseId);

            if(cu.getCompanyStatus()==3&&!companyLicense.getCertNo().equals(companyLicenseDto.getCertNo())){
                throw new FreightException("不能更换营业执照");
            }

            ObjectUtil.copyPropertiesIgnoreNull(companyLicenseDto, companyLicense);
            logContent = "修改货主信息";
        } else {
            companyLicense = new CompanyLicense();
            ObjectUtil.copyPropertiesIgnoreNull(companyLicenseDto, companyLicense);
            logContent = "上传货主信息";
        }

        companyLicense = companyLicenseDao.save(companyLicense);

        cu.setCompanyLicenseId(companyLicense.getId());

        if(user.getUserType() == 2 && cu.getCompanyStatus() == 1){
            cu.setCompanyStatus(1);
        }else {
            cu.setCompanyStatus(2);
        }


        u.setNickName(companyLicense.getCompanyName());
        userService.save(u);
        companyUserService.save(cu);

        //操作记录
        operationLogService.saveOperationLog(1,logContent,userId.toString());

        return "保存成功";
    }

}